/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.front.web.pay.ali;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.utils.ali.util.AlipayNotify;
import com.thinkgem.jeesite.modules.config.entity.ali.ConfigAlipay;
import com.thinkgem.jeesite.modules.config.service.ali.ConfigAlipayService;
import com.thinkgem.jeesite.modules.pay.entity.log.EcPayLog;
import com.thinkgem.jeesite.modules.pay.service.log.EcPayLogService;
import com.thinkgem.jeesite.modules.shop.constant.order.ShopOrderConstant;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;

/**
 * ALIPAYService
 * @author Egan
 * @version 2016-02-15
 */
@Service
@Transactional(readOnly = true)
public class ALIPayService {
	private static Log log = LogFactory.getLog(ALIPayService.class);
	@Autowired EcPayLogService ecPayLogService;
	@Autowired ShopOrderService shopOrderService;
	@Autowired ConfigAlipayService configAlipayService;
	@Transactional(readOnly = false)
    public void forResult(Map requestParams,HttpServletRequest request) throws Exception {
		Map<String,String> params = new HashMap<String,String>();
		ConfigAlipay configAlipay = configAlipayService.getConfigAlipay();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		if (log.isDebugEnabled()) {
			log.debug("requestParams.toString()：" + requestParams.toString());
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
		//交易金额
		String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"),"UTF-8");
		//成交时间
		String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"),"UTF-8");
		//成交类型
		String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"),"UTF-8");
		String payment_type = new String(request.getParameter("payment_type").getBytes("ISO-8859-1"),"UTF-8");
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		EcPayLog ecPayLog = new EcPayLog();
		ecPayLog.setCoNum(out_trade_no);
		ecPayLog.setAmount(new BigDecimal(total_fee));
    	ecPayLog.setMerChantid(seller_id);
    	ecPayLog.setOrderNo(trade_no);
    	ecPayLog.setAccDate(notify_time);
    	ecPayLog.setOrgCode(seller_id);
    	ecPayLog.setPayDate(notify_time);
    	ecPayLog.setPayType(payment_type);
    	ecPayLog.setBankId("95518");
    	ecPayLog.setBankName("支付宝");
		if(AlipayNotify.verify(params,configAlipay)){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				//如果有做过处理，不执行商户的业务程序
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
				//TODO
				ecPayLog.setPayFlag("1");
			} else if (trade_status.equals("TRADE_SUCCESS")){
				ecPayLog.setPayFlag("1");
			}

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			ecPayLog.setPayFlag("2");
		}
		
		ecPayLogService.deletePayFlagByLog(ecPayLog);
        ecPayLogService.save(ecPayLog);
        ShopOrder order = new ShopOrder();
        SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        order.setPayTime(sdf.parse(notify_time));
		order.setCode(out_trade_no);
		ShopOrder shorder = shopOrderService.findByCoNum(out_trade_no);
		if(shorder.getStatus()==ShopOrderConstant.ORDER_WAIT_PAYMENT){
		    order.setStatus(ShopOrderConstant.ORDER_PAYMENT_DONE);
		}
		
		shopOrderService.updateOrderForPaySuccess(order);
    }
	
	@Transactional(readOnly = false)
    public Map<String,String> forReturn(Map requestParams,HttpServletRequest request) throws Exception {
		Map<String,String> resultMap = new HashMap<String,String>();
		Map<String,String> params = new HashMap<String,String>();
		ConfigAlipay configAlipay = configAlipayService.getConfigAlipay();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		if (log.isDebugEnabled()) {
			log.debug("requestParams.toString()：" + requestParams.toString());
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
		//交易金额
		String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"),"UTF-8");
		//成交时间
		String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"),"UTF-8");
		//成交类型
		String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"),"UTF-8");
		String payment_type = new String(request.getParameter("payment_type").getBytes("ISO-8859-1"),"UTF-8");
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		EcPayLog ecPayLog = new EcPayLog();
		ecPayLog.setCoNum(out_trade_no);
		ecPayLog.setAmount(new BigDecimal(total_fee));
    	ecPayLog.setMerChantid(seller_id);
    	ecPayLog.setOrderNo(trade_no);
    	ecPayLog.setAccDate(notify_time);
    	ecPayLog.setOrgCode(seller_id);
    	ecPayLog.setPayDate(notify_time);
    	ecPayLog.setPayType(payment_type);
    	ecPayLog.setBankId("95518");
    	ecPayLog.setBankName("支付宝");
		if(AlipayNotify.verify(params,configAlipay)){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				//如果有做过处理，不执行商户的业务程序
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
				//TODO
				ecPayLog.setPayFlag("0");
				resultMap.put("message", "fail");
			} else if (trade_status.equals("TRADE_SUCCESS")){
				ecPayLog.setPayFlag("1");
				ShopOrder order = new ShopOrder();
				ShopOrder shorder = shopOrderService.findByCoNum(out_trade_no);
		        
				order.setCode(out_trade_no);
				 SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				order.setPayTime(sdf.parse(notify_time));
				if(shorder.getStatus()==ShopOrderConstant.ORDER_WAIT_PAYMENT){
                    order.setStatus(ShopOrderConstant.ORDER_PAYMENT_DONE);
                }
				//order.setStatus(ShopOrderConstant.ORDER_PAYMENT_DONE);
				shopOrderService.updateOrderForPaySuccess(order);
				//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
				resultMap.put("message", "success");
				resultMap.put("total_fee", total_fee);
				resultMap.put("coNum", out_trade_no);
			}
		}else{//验证失败
			ecPayLog.setPayFlag("2");
			resultMap.put("message", "fail");
		}
		ecPayLogService.deletePayFlagByLog(ecPayLog);
        ecPayLogService.save(ecPayLog);
		return resultMap;
	}
}